package com.aipartner.service.impl;

import com.aipartner.dto.*;
import com.aipartner.entity.*;
import com.aipartner.mapper.*;
import com.aipartner.service.AdminService;
import com.aipartner.util.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * 管理员服务实现类
 */
@Slf4j
@Service
public class AdminServiceImpl implements AdminService {
    
    @Autowired
    private AdminUserMapper adminUserMapper;
    
    @Autowired
    private AdminOperationLogMapper operationLogMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private CreditsTransactionMapper creditsTransactionMapper;
    
    @Autowired
    private CreditsOrderMapper creditsOrderMapper;
    
    @Autowired
    private AiImageHistoryMapper aiImageHistoryMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Override
    public LoginResponse login(AdminLoginRequest request, String ip) {
        // 查询管理员用户
        LambdaQueryWrapper<AdminUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminUser::getUsername, request.getUsername());
        wrapper.eq(AdminUser::getStatus, 1); // 只查询启用状态的管理员
        
        AdminUser adminUser = adminUserMapper.selectOne(wrapper);
        if (adminUser == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 验证密码（使用BCrypt算法）
        log.info("管理员登录验证开始 - 用户名: {}", request.getUsername());
        
        boolean passwordMatches = passwordEncoder.matches(request.getPassword(), adminUser.getPassword());
        
        if (!passwordMatches) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 更新登录信息
        updateLoginInfo(adminUser.getId(), ip);
        
        // 生成JWT Token
        String token = jwtUtil.generateToken(adminUser.getId().toString(), adminUser.getUsername());
        
        // 构建响应
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        
        log.info("管理员登录成功 - 用户名: {}, IP: {}", request.getUsername(), ip);
        return response;
    }
    
    @Override
    public AdminUser getByUsername(String username) {
        LambdaQueryWrapper<AdminUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminUser::getUsername, username);
        wrapper.eq(AdminUser::getStatus, 1);
        return adminUserMapper.selectOne(wrapper);
    }
    
    @Override
    public AdminUserResponse getAdminById(Long id) {
        AdminUser adminUser = adminUserMapper.selectById(id);
        if (adminUser == null) {
            return null;
        }
        
        AdminUserResponse response = new AdminUserResponse();
        BeanUtils.copyProperties(adminUser, response);
        return response;
    }
    
    @Override
    public void updateLoginInfo(Long adminId, String ip) {
        AdminUser updateUser = new AdminUser();
        updateUser.setId(adminId);
        updateUser.setLastLoginTime(LocalDateTime.now());
        updateUser.setLastLoginIp(ip);
        
        // 增加登录次数
        AdminUser currentUser = adminUserMapper.selectById(adminId);
        if (currentUser != null) {
            updateUser.setLoginCount((currentUser.getLoginCount() != null ? currentUser.getLoginCount() : 0) + 1);
        }
        
        adminUserMapper.updateById(updateUser);
    }
    
    @Override
    public void saveOperationLog(AdminOperationLog log) {
        operationLogMapper.insert(log);
    }
    
    @Override
    public Page<AdminOperationLog> getOperationLogs(Page<AdminOperationLog> page, Long adminId, String module, String operation) {
        LambdaQueryWrapper<AdminOperationLog> wrapper = new LambdaQueryWrapper<>();
        
        if (adminId != null) {
            wrapper.eq(AdminOperationLog::getAdminId, adminId);
        }
        if (module != null && !module.trim().isEmpty()) {
            wrapper.eq(AdminOperationLog::getModule, module);
        }
        if (operation != null && !operation.trim().isEmpty()) {
            wrapper.like(AdminOperationLog::getOperation, operation);
        }
        
        wrapper.orderByDesc(AdminOperationLog::getCreateTime);
        
        return operationLogMapper.selectPage(page, wrapper);
    }
    
    @Override
    public AdminStatsResponse getDashboardStats() {
        AdminStatsResponse stats = new AdminStatsResponse();
        
        try {
            // 统计用户数据
            Long totalUsers = userMapper.selectCount(null);
            stats.setTotalUsers(totalUsers);
            
            // 统计VIP用户数
            LambdaQueryWrapper<User> vipWrapper = new LambdaQueryWrapper<>();
            vipWrapper.gt(User::getVipLevel, 0);
            Long vipUsers = userMapper.selectCount(vipWrapper);
            stats.setVipUsers(vipUsers);
            
            // 统计今日新增用户
            LocalDateTime todayStart = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
            LambdaQueryWrapper<User> todayWrapper = new LambdaQueryWrapper<>();
            todayWrapper.ge(User::getCreateTime, todayStart);
            Long todayNewUsers = userMapper.selectCount(todayWrapper);
            stats.setTodayNewUsers(todayNewUsers);
            
            // 统计积分相关数据
            // 积分总发放 = 所有用户的totalCreditsEarned总和
            // 这里简化处理，直接统计积分交易记录
            LambdaQueryWrapper<CreditsTransaction> earnWrapper = new LambdaQueryWrapper<>();
            earnWrapper.in(CreditsTransaction::getTransactionType, "purchase", "earn");
            earnWrapper.eq(CreditsTransaction::getStatus, "completed");
            Long totalCreditsEarned = creditsTransactionMapper.selectList(earnWrapper).stream()
                    .mapToLong(CreditsTransaction::getAmount)
                    .sum();
            stats.setTotalCredits(totalCreditsEarned);
            
            // 积分总消耗
            LambdaQueryWrapper<CreditsTransaction> consumeWrapper = new LambdaQueryWrapper<>();
            consumeWrapper.eq(CreditsTransaction::getTransactionType, "consume");
            consumeWrapper.eq(CreditsTransaction::getStatus, "completed");
            Long totalCreditsConsumed = creditsTransactionMapper.selectList(consumeWrapper).stream()
                    .mapToLong(transaction -> Math.abs(transaction.getAmount()))
                    .sum();
            stats.setTotalConsumed(totalCreditsConsumed);
            
            // 订单统计
            Long totalOrders = creditsOrderMapper.selectCount(null);
            stats.setTotalOrders(totalOrders);
            
            // 收入统计（已支付的订单）
            LambdaQueryWrapper<CreditsOrder> paidWrapper = new LambdaQueryWrapper<>();
            paidWrapper.eq(CreditsOrder::getStatus, "paid");
            Double totalRevenue = creditsOrderMapper.selectList(paidWrapper).stream()
                    .mapToDouble(order -> order.getAmount().doubleValue())
                    .sum();
            stats.setTotalRevenue(totalRevenue);
            
            // AI生图统计
            Long aiImageCount = aiImageHistoryMapper.selectCount(null);
            stats.setAiImageCount(aiImageCount);
            
            // 今日AI生图
            LambdaQueryWrapper<AiImageHistory> todayAiWrapper = new LambdaQueryWrapper<>();
            todayAiWrapper.ge(AiImageHistory::getCreateTime, todayStart);
            Long todayAiImageCount = aiImageHistoryMapper.selectCount(todayAiWrapper);
            stats.setTodayAiImageCount(todayAiImageCount);
            
        } catch (Exception e) {
            log.error("获取仪表盘统计数据失败", e);
            // 如果查询失败，返回默认值
            stats.setTotalUsers(0L);
            stats.setVipUsers(0L);
            stats.setTodayNewUsers(0L);
            stats.setTotalCredits(0L);
            stats.setTotalConsumed(0L);
            stats.setTotalOrders(0L);
            stats.setTotalRevenue(0.0);
            stats.setAiImageCount(0L);
            stats.setTodayAiImageCount(0L);
        }
        
        return stats;
    }
    
    @Override
    public AdminUser getProfile(Long adminId) {
        return adminUserMapper.selectById(adminId);
    }
    
    @Override
    @Transactional
    public boolean updateProfile(Long adminId, AdminProfileRequest request) {
        try {
            AdminUser adminUser = new AdminUser();
            adminUser.setId(adminId);
            adminUser.setNickname(request.getDisplayName());
            adminUser.setEmail(request.getEmail());
            adminUser.setPhone(request.getPhone());
            adminUser.setDescription(request.getDescription());
            
            if (request.getAvatar() != null && !request.getAvatar().trim().isEmpty()) {
                adminUser.setAvatar(request.getAvatar());
            }
            
            return adminUserMapper.updateById(adminUser) > 0;
        } catch (Exception e) {
            log.error("更新管理员个人信息失败", e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean updatePassword(Long adminId, AdminPasswordRequest request) {
        try {
            // 验证当前密码
            AdminUser currentUser = adminUserMapper.selectById(adminId);
            if (currentUser == null) {
                return false;
            }
            
            if (!passwordEncoder.matches(request.getCurrentPassword(), currentUser.getPassword())) {
                throw new RuntimeException("当前密码不正确");
            }
            
            // 更新密码
            AdminUser adminUser = new AdminUser();
            adminUser.setId(adminId);
            adminUser.setPassword(passwordEncoder.encode(request.getNewPassword()));
            
            return adminUserMapper.updateById(adminUser) > 0;
        } catch (Exception e) {
            log.error("修改管理员密码失败", e);
            throw new RuntimeException(e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public boolean updateAvatar(Long adminId, String avatarUrl) {
        try {
            AdminUser adminUser = new AdminUser();
            adminUser.setId(adminId);
            adminUser.setAvatar(avatarUrl);
            
            return adminUserMapper.updateById(adminUser) > 0;
        } catch (Exception e) {
            log.error("更新管理员头像失败", e);
            return false;
        }
    }
}
